﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YY.Admin.ViewModels.Control
{
    public class PaginationDataGridViewModel<T> : BindableBase
    {
        private int _pageIndex = 1;
        private int _pageSize = 1;
        private int _totalCount;
        private ObservableCollection<T> _data;
        private string _pageInfo;

        public int PageIndex
        {
            get => _pageIndex;
            set => SetProperty(ref _pageIndex, value);
        }

        public int MaxPageCount => (int)Math.Ceiling((double)_totalCount / _pageSize);

        public ObservableCollection<T> Data
        {
            get => _data;
            set => SetProperty(ref _data, value);
        }

        public string PageInfo
        {
            get => _pageInfo;
            set => SetProperty(ref _pageInfo, value);
        }

        public DelegateCommand PageUpdatedCmd { get; private set; }

        private Func<int, int, Task<(IEnumerable<T> data, int totalCount)>> _fetchData;

        public PaginationDataGridViewModel(Func<int, int, Task<(IEnumerable<T> data, int totalCount)>> fetchData)
        {
            _fetchData = fetchData;
            PageUpdatedCmd = new DelegateCommand(OnPageUpdated);
        }

        private async void OnPageUpdated()
        {
            await LoadData(PageIndex);
        }

        public async Task LoadData(int pageIndex)
        {
            var (data, totalCount) = await _fetchData(pageIndex, _pageSize);
            Data = new ObservableCollection<T>(data);
            _totalCount = totalCount;
            // 通知分页总数变化
            RaisePropertyChanged(nameof(MaxPageCount));
            // 更新分页信息
            PageInfo = $"Page {PageIndex} of {MaxPageCount}";
        }
    }


}
